<template>
  <div class="app-container">
    <el-form :inline="true" @submit.native.prevent>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-plus"
          @click="add"
        >{{ $t('add') }}
        </el-button>
      </el-form-item>
    </el-form>
    <el-table
      :data="groupList"
      style="width: 100%"
      row-key="id"
      default-expand-all
      :tree-props="{children: 'children'}"
    >
      <el-table-column width="70"/>
      <el-table-column prop="name" :label="$t('name')"/>
      <el-table-column prop="address" :label="$t('address')"/>
      <el-table-column :label="$t('function')" width="250">
        <template slot-scope="scope">
          <el-button
            type="text"
            icon="el-icon-folder-add"
            @click="showAddGroup(scope.row)"
          >{{ $t('add') }}
          </el-button>
          <el-button
            type="text"
            icon="el-icon-edit"
            @click="edit(scope.row)"
          >{{ $t('edit') }}
          </el-button>
          <el-button
            type="text"
            icon="el-icon-cpu"
            @click="addDevice(scope.row)"
          >{{ $t('device') }}
          </el-button>
          <el-button
            style="color:#F56C6C "
            type="text"
            icon="el-icon-folder-delete"
            @click="del(scope.row)"
          >{{ $t('delete') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog
      :visible.sync="dialogFormVisible"
      top="15px"
    >
      <el-form
        label-width="120px"
        :model="group"
      >
        <el-form-item :label="$t('name')">
          <el-input v-model="group.name"/>
        </el-form-item>
        <el-form-item :label="$t('map')">
          <div
            ref="map"
            style="height: 350px; width: 100%;"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">{{ $t('cancel') }}</el-button>
        <el-button type="primary" @click="addOrUpdate">{{ $t('confirm') }}</el-button>
      </div>
    </el-dialog>

    <el-dialog
      :visible.sync="deviceFormVisible"
      top="15px"
    >
      <user-device-choice :user-id="userId" :group-id="group.id"/>
    </el-dialog>

  </div>
</template>

<script>
import { cancelNotice, successNotice } from '@/util/common'
import { getUserId } from '@/util/storage'
import {
  deleteDeviceBelongGroup,
  insertDeviceBelongGroup,
  treeDeviceBelongGroup,
  updateDeviceBelongGroup
} from '@/api/iot/iotDeviceBelongGroupApi'
import UserDeviceChoice from './UserDeviceChoice'
import { addMapClickListener, clearAllMarket, makeMap, makeMarket } from '@/util/mapTool'

let map = {}
let marker = {}
export default {
  name: 'GroupManage',
  components: { UserDeviceChoice },
  data() {
    return {
      groupList: [],
      group: {
        name: '',
        lat: null,
        lng: null
      },
      userId: parseInt(getUserId()),
      deviceList: [],
      dialogFormVisible: false,
      deviceFormVisible: false
    }
  },
  watch: {
    dialogFormVisible: {
      deep: true,
      handler(val) {
        if (this.dialogFormVisible) {
          const that = this
          this.$nextTick(function() {
            if (that.group.lat && that.group.lng) {
              map = makeMap(that.$refs.map, that.group.lat, that.group.lng)
              marker = makeMarket(map, that.group.lat, that.group.lng)
            } else {
              map = makeMap(that.$refs.map)
            }
            addMapClickListener(map, (event) => {
              clearAllMarket(map)
              marker = makeMarket(map, event.latLng.lat, event.latLng.lng)
              that.group.lat = event.latLng.lat
              that.group.lng = event.latLng.lng
              // addMarketClickListener(map, marker, () => {
              //   clearAllMarket(map)
              // })
            })
          })
        }
      }
    }
  },
  created() {
    this.treeDeviceBelongGroup()
  },
  methods: {
    add() {
      this.group = {
        name: ''
      }
      this.dialogFormVisible = true
    },
    showAddGroup(item) {
      this.group = {
        parentId: item.id,
        name: ''
      }
      this.dialogFormVisible = true
    },
    edit(item) {
      this.group = item
      this.dialogFormVisible = true
    },
    addDevice(item) {
      this.group = item
      this.deviceFormVisible = true
    },
    update(item) {
      updateDeviceBelongGroup({
        groupId: item.id,
        name: item.name
      }).then(res => {
        const { code } = res
        if (code === '200') {
          successNotice(this)
        }
        this.treeDeviceBelongGroup()
      })
    },
    statusChange() {
      this.treeDeviceBelongGroup()
    },
    treeDeviceBelongGroup() {
      treeDeviceBelongGroup({
        userId: this.userId
      }).then(res => {
        const { code, data } = res
        if (code === '200') {
          this.groupList = data
        }
      })
    },
    addOrUpdate() {
      let r
      if (this.group.groupId) {
        r = updateDeviceBelongGroup(this.group)
      } else {
        r = insertDeviceBelongGroup(this.group)
      }
      r.then(res => {
        const { code } = res
        if (code === '200') {
          successNotice(this)
          this.dialogFormVisible = false
        }
        this.treeDeviceBelongGroup()
      })
    },
    del(item) {
      const that = this
      this.$confirm(that.$t('delete'), that.$t('prompt'), {
        confirmButtonText: that.$t('confirm'),
        cancelButtonText: that.$t('cancel'),
        type: 'warning'
      })
        .then(function() {
          deleteDeviceBelongGroup({
            groupId: item.id
          }).then(res => {
            const { code } = res
            if (code === '200') {
              successNotice(that)
              that.treeDeviceBelongGroup()
            }
          })
        })
        .catch(function() {
          cancelNotice(that)
        })
    }
  }
}
</script>
